<template>
  <el-form
    ref="loginForm"
    :model="form"
    :rules="rules"
    label-width="0"
    size="large"
  >
    <el-form-item prop="user">
      <el-input
        v-model="form.user"
        prefix-icon="el-icon-user"
        clearable
        :placeholder="$t('login.userPlaceholder')"
      >
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        prefix-icon="el-icon-lock"
        clearable
        show-password
        :placeholder="$t('login.PWPlaceholder')"
      ></el-input>
    </el-form-item>

    <el-form-item prop="verCode">
      <el-row :gutter="10">
        <el-col :span="12" style="margin-top: 3px">
          <el-input
            v-model="form.verCode"
            prefix-icon="el-icon-lock"
            clearable
            :placeholder="$t('login.verificationCode')"
          ></el-input>
        </el-col>
        <el-col :span="12">
          <el-image
            :src="verImg"
            style="width: 150px; height: 50px"
            @click="getCode"
          ></el-image>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item style="margin-bottom: 10px; margin-top: -15px">
      <el-col :span="12">
        <el-checkbox label="记住密码" v-model="form.remberLogin"></el-checkbox>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        style="width: 100%"
        :loading="islogin"
        round
        @click="loginRef"
        >{{ $t("login.signIn") }}</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { ref, onMounted } from "vue";
import base from "@/utils/base64";
import $tool from "@/utils/tool";
import axios from "axios";
import Api from "@/api/index.js";
import { ElMessage } from "element-plus";
import config from '@/config/index.js'
export default {
  data() {
    return {
      userType: "admin",
      form: {
        user: "admin",
        password: "123456",
        autologin: false,
        remberLogin: true,
        verCode: "",
        loginlang: "login.userPlaceholder",
      },
      rules: {
        user: [
          {
            required: true,
            message: this.$t("login.userError"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("login.PWError"),
            trigger: "blur",
          },
        ],
        verCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      islogin: false,

      verImg: "",
      uuid: "",
      // token: '',
    };
  },
  watch: {
    userType(val) {},
  },
  created() {
    let lang = ["zh_CN", "en", "zh_TW"];
    lang.forEach((ele) => {
      fetch(`${config.API_URL}/resources/scripts/lang/lang-${ele}.js`)
        .then((response) => response.json()) // 解析 JSON 响应
        .then((data) => {
          this.$i18n.setLocaleMessage(
            ele,
            Object.assign(this.$i18n.messages[ele], data)
          );
        })
        .catch((error) => {
          console.error("Error fetching locale messages:", error);
        });
    });
  },
  mounted() {
    this.form.verCode = "";
    this.getCode();
    window.addEventListener("keydown", this.keyDown, { passive: true });
    let loginForm = this.$TOOL.data.get("loginForm");
    if (loginForm) {
      this.form.user = loginForm.userName;
      this.form.password = this.$TOOL.crypto.AES.decrypt(
        loginForm.password,
        "NdOvJKcXHsR0y2cYMIAIFw=="
      );
    }
    let h;
    var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    if (!iOS) {
      h = window.innerHeight;
    } else {
      h = screen.height;
    }
    this.$TOOL.data.set("windowHeight", h);
  },
  beforeUnmount() {
    window.removeEventListener("keydown", this.keyDown)
  },
  methods: {
    keyDown(e) {
      if (e.keyCode === 13 || e.keyCode === 100) {
        this.loginRef();
      }
    },
    async getCode() {
      var res = await this.$API.auth.captchaImage.post();
      if (res.code == 200) {
        this.verImg = "data:image/gif;base64," + res.img;
        this.uuid = res.uuid;
      } else {
        this.islogin = false;
        return false;
      }
    },
    loginRef() {
      if (this.form.user == "") {
        this.$message.warning("请输入用户名");
      }
      if (this.form.password == "") {
        this.$message.warning("请输入密码");
      }
      if (this.form.verCode == "") {
        this.$message.warning("请输入验证码");
      }
      if (
        this.form.user !== "" &&
        this.form.password !== "" &&
        this.form.verCode !== ""
      ) {
        window.removeEventListener("keydown", this.keyDown);
        this.login();
      }
    },
    async login() {
      if (this.form.remberLogin == true) {
        this.$TOOL.data.set("loginForm", {
          userName: this.form.user,
          password: this.$TOOL.crypto.AES.encrypt(
            this.form.password,
            "NdOvJKcXHsR0y2cYMIAIFw=="
          ),
        });
      }
      this.islogin = true; //转f
      var params = {
        userName: this.form.user,
        password: this.$TOOL.crypto.AES.encrypt(
          this.form.password,
          "NdOvJKcXHsR0y2cYMIAIFw=="
        ),
        code: this.form.verCode,
        uuid: this.uuid,
      };
      var res = await this.$API.auth.login.post(params);
      if (res.code == 200) {
        this.token = res.token;
        $tool.cookie.set("TOKEN", res.token);
        this.$TOOL.data.set("USER_INFO", { name: res.userName });
        this.getUserInfo();
      } else {
        this.form.verCode = "";
        this.islogin = false;
        window.addEventListener("keydown", this.keyDown, { passive: true });
        this.getCode();
      }
    },
    async getUserInfo() {
      var res = await this.$API.auth.getBaseUserInfo.post();
      if (res.code == 200) {
        res.data.websocketUrl = res.websocketUrl;
        this.$TOOL.data.set("USER_INFO", res.data);
        this.getMenuList();
      }
    },
    async getMenuList() {
      var params = {
        name: "menu",
      };
      let res = await this.$API.system.menu.routerList.post(params);
      if (res.code == 200) {
        this.$TOOL.data.set("MENU", res.data);
        this.$emit('loginSuccess')
        this.$router.replace({
          path: "/",
        });
        this.$message.success("Login Success 登录成功");
        this.islogin = false;
      }
    },
  },
};
</script>

<style></style>
